package com.huanwang.commonlibrary.networkframework

import android.util.Log
import com.huanwang.commonlibrary.base.BaseApplication
import com.huanwang.commonlibrary.utils.NetUtils.isNetworkConnected
import okhttp3.CacheControl
import okhttp3.FormBody
import okhttp3.Interceptor
import okhttp3.Response
import java.io.IOException
import java.util.*

/**
 * Created by mypc on 2018/4/14.
 */
object OKhttpInterceptor {
    //缓存的拦截器
    @JvmField
    val cacheInterceptor: Interceptor = object : Interceptor {
        @Throws(IOException::class)
        override fun intercept(chain: Interceptor.Chain): Response {
            var request = chain.request()
            if (!isNetworkConnected(BaseApplication.context)) {
                request = request.newBuilder()
                    .cacheControl(CacheControl.FORCE_CACHE)
                    .build()
            }
            val response = chain.proceed(request)
            if (isNetworkConnected(BaseApplication.context)) {
                val maxAge = 60 * 60 * 24 // 有网络的时候从缓存1天后失效
                response.newBuilder()
                    .removeHeader("Pragma") // 清除头信息，因为服务器如果不支持，会返回一些干扰信息，不清除下面无法生效
                    .header("Cache-Control", "public, max-age=$maxAge")
                    .build()
            } else {
                // 无网络时，设置超时为4周
                val maxStale = 60 * 60 * 24 * 28
                response.newBuilder()
                    .removeHeader("Pragma")
                    .header("Cache-Control", "public, only-if-cached, max-stale=$maxStale")
                    .build()
            }
            return response
        }
    }

    /**
     * 公共参数拦截器
     */
    var map: MutableMap<String, String> =
        HashMap()
    @JvmField
    var commonParamsInterceptor: Interceptor = object : Interceptor {
        //拦截的方法
        @Throws(IOException::class)
        override fun intercept(chain: Interceptor.Chain): Response {

            //获取到请求
            var request = chain.request()
            //获取请求的方式
            val method = request.method
            //获取请求的路径
            val oldUrl = request.url.toString()
            Log.e(
                "---拦截器",
                request.url.toString() + "---" + request.method + "--" + request.header("User-agent")
            )

            //要添加的公共参数...map
            map["source"] = "android"
            if ("GET" == method) {
                val stringBuilder =
                    StringBuilder() //创建一个stringBuilder
                stringBuilder.append(oldUrl)
                if (oldUrl.contains("?")) {
                    //?在最后面....2类型
                    if (oldUrl.indexOf("?") == oldUrl.length - 1) {
                    } else {
                        //3类型...拼接上&
                        stringBuilder.append("&")
                    }
                } else {
                    //不包含? 属于1类型,,,先拼接上?号
                    stringBuilder.append("?")
                }

                //添加公共参数....
                for ((key, value) in map) {
                    //拼接
                    stringBuilder.append(key)
                        .append("=")
                        .append(value)
                        .append("&")
                }

                //删掉最后一个&符号
                if (stringBuilder.indexOf("&") != -1) {
                    stringBuilder.deleteCharAt(stringBuilder.lastIndexOf("&"))
                }
                val newUrl = stringBuilder.toString() //新的路径

                //拿着新的路径重新构建请求
                request = request.newBuilder()
                    .url(newUrl)
                    .build()
            } else if ("POST" == method) {
                //先获取到老的请求的实体内容
                val oldRequestBody = request.body //....之前的请求参数,,,需要放到新的请求实体内容中去

                //如果请求调用的是上面doPost方法
                if (oldRequestBody is FormBody) {
                    val oldBody = oldRequestBody

                    //构建一个新的请求实体内容
                    val builder = FormBody.Builder()
                    //1.添加老的参数
                    for (i in 0 until oldBody.size) {
                        builder.add(oldBody.name(i), oldBody.value(i))
                    }
                    //2.添加公共参数
                    for ((key, value) in map) {
                        builder.add(key, value)
                    }
                    val newBody = builder.build() //新的请求实体内容

                    //构建一个新的请求
                    request = request.newBuilder()
                        .url(oldUrl)
                        .post(newBody)
                        .build()
                }
            }
            return chain.proceed(request)
        }
    }
}